package com.jydd.investtheretreatoldhouse;

import android.Manifest;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.view.WindowManager;

import java.util.ArrayList;
import java.util.Collections;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.NotificationManagerCompat;
import ecomm.lib_comm.permission.UsesPermission;

import static android.provider.Settings.EXTRA_APP_PACKAGE;
import static android.provider.Settings.EXTRA_CHANNEL_ID;

/**
 * created by 韦敏敏
 * on 2019/12/25
 */
public class WelcomeActivity extends AppCompatActivity {
    private AlertDialog alertDialog;
    public static final int REQUEST_NOTIFICATION_PERMISSION_CODE = 1;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().addFlags(
                WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
        );
        alertDialog = new AlertDialog.Builder(this)
                .setTitle("提醒")
                .setMessage("请打开通知权限")
                .setCancelable(false)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // 手动打开通知权限
                        jumpToOpenTheNotification();
                    }
                }).create();

        // 安卓6.0以下无需进行权限判断
        if(Build.VERSION.SDK_INT < Build.VERSION_CODES.M){
            checkNotifySetting();
        } else {
            requestPermissons();
        }
    }

    private void jumpToOpenTheNotification() {
        Intent intent = new Intent();
        intent.setAction(Settings.ACTION_APP_NOTIFICATION_SETTINGS);
        // 这种方案适用于API 26, 即8.0（含8.0）以上可以用
        intent.putExtra(EXTRA_APP_PACKAGE, getPackageName());
        intent.putExtra(EXTRA_CHANNEL_ID, getApplicationInfo().uid);
        // 这种方案适用于API21-25, 即5.0-7.1之间的版本可用
        intent.putExtra("app_package", getPackageName());
        intent.putExtra("app_uid", getApplicationInfo().uid);
        // 小米6 -MIUI9.6-8.0.0系统，是个特例，通知设置界面只能控制"允许使用通知圆点"——然而这个玩意并没有卵用，我想对雷布斯说：I'm not ok!!!
        //  if ("MI 6".equals(Build.MODEL)) {
        //      intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        //      Uri uri = Uri.fromParts("package", getPackageName(), null);
        //      intent.setData(uri);
        //      // intent.setAction("com.android.settings/.SubSettings");
        //  }
        startActivity(intent);
        startActivityForResult(intent, REQUEST_NOTIFICATION_PERMISSION_CODE);
    }

    private void requestPermissons() {
        ArrayList<String> permissions = new ArrayList<>();
        Collections.addAll(permissions,
                Manifest.permission.INTERNET,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.REQUEST_INSTALL_PACKAGES,
                Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.READ_PHONE_STATE,
                Manifest.permission.VIBRATE
        );
        String[] aar = permissions.toArray(new String[0]);
        new UsesPermission(WelcomeActivity.this, getApplicationContext(), aar){
            @Override
            protected String onCancelTips(int viewCancelCount, @NonNull ArrayList<String> permissions, boolean isFinal) {
                if(viewCancelCount < 3){
                    //                    Toast.makeText(WelcomeActivity.this, "请授权软件运行必须的权限" + permissions.toString() , Toast.LENGTH_SHORT).show();
                    return "请授权软件运行必须的权限" + "[{Names}]";
                } else {
                    finish();
                    // Dalvik VM的本地方法
                    android.os.Process.killProcess(android.os.Process.myPid());
                }
                return super.onCancelTips(viewCancelCount, permissions, isFinal);
            }

            @Override
            protected String onTips(int viewTipsCount, @NonNull ArrayList<String> permissions, boolean isFinal) {
                return "请授权 ：" + "权限：[{Names}]";
            }

            @Override
            protected void onTrue(@NonNull ArrayList<String> lowerPermissions) {
                // 低版本权限
                super.onTrue(lowerPermissions);
            }

            @Override
            protected void onFalse(@NonNull ArrayList<String> rejectFinalPermissions, @NonNull ArrayList<String> rejectPermissions, @NonNull ArrayList<String> invalidPermissions) {
                // 永久拒绝、拒绝及无效权限
                super.onFalse(rejectFinalPermissions, rejectPermissions, invalidPermissions);
            }

            @Override
            protected void onComplete(@NonNull ArrayList<String> resolvePermissions, @NonNull ArrayList<String> lowerPermissions, @NonNull ArrayList<String> rejectFinalPermissions, @NonNull ArrayList<String> rejectPermissions, @NonNull ArrayList<String> invalidPermissions) {
                if(rejectFinalPermissions.size() == 0 && rejectPermissions.size() == 0){
                    // 检查通知权限是否开启
                    checkNotifySetting();
                } else {
                    // ToDo
                }
                super.onComplete(resolvePermissions, lowerPermissions, rejectFinalPermissions, rejectPermissions, invalidPermissions);
            }
        };
    }

    private void checkNotifySetting() {
        NotificationManagerCompat manager = NotificationManagerCompat.from(this);
        // areNotificationsEnabled方法的有效性官方最低支持到API19，低于19的仍可调用此方法，不过只会返回true，即默认用户已经开启通知
        boolean isOpen = manager.areNotificationsEnabled();
        if(isOpen){
            // 确保无永久拒绝权限并且无拒绝权限时，执行业务操作
            // 继续授权相关权限
            Intent intent = new Intent();
            intent.setClass(WelcomeActivity.this, MainActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            WelcomeActivity.this.startActivity(intent);
            finish();
        } else {
            // 手动去开启通知权限
            alertDialog.show();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == REQUEST_NOTIFICATION_PERMISSION_CODE){
            checkNotifySetting();
        }
    }
}
